﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using Fiddler;
using System.Threading;
using CSharp.Libs.Net;
using System.IO;

namespace FirstFiddlerApp
{

         
    /// <summary>
    /// Interaktionslogik für MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        static bool bUpdateTitle = true;
        static Proxy oSecureEndpoint;
        static string sSecureEndpointHostname = "localhost";
        
        List<Fiddler.Session> oAllSessions = new List<Fiddler.Session>();



        public MainWindow()
        {
            InitializeComponent();

            this.Dispatcher.Invoke(
                System.Windows.Threading.DispatcherPriority.Normal,
                new Action(delegate()
                {
                    txtResult.Text = String.Concat(txtResult.Text, "Inited", Environment.NewLine);
                }
                ));


            Fiddler.FiddlerApplication.OnNotification += delegate(
                object sender,
                NotificationEventArgs oNEA)
            {
                this.Dispatcher.Invoke(
                    System.Windows.Threading.DispatcherPriority.Normal,
                    new Action(delegate()
                    {
                        txtResult.Text = String.Concat(txtResult.Text, "** NotifyUser: " + oNEA.NotifyString, Environment.NewLine);
                    }
                    ));
            };

            Fiddler.FiddlerApplication.Log.OnLogString += delegate(
                object sender,
                LogEventArgs oLEA)
            {
                this.Dispatcher.Invoke(
                    System.Windows.Threading.DispatcherPriority.Normal,
                    new Action(delegate()
                    {
                        txtResult.Text = String.Concat(txtResult.Text, "** LogString: " + oLEA.LogString, Environment.NewLine);
                    }
                    ));
            };


            Fiddler.FiddlerApplication.BeforeRequest += delegate(
                Fiddler.Session oS)
            {
                // Console.WriteLine("Before request for:\t" + oS.fullUrl);
                // In order to enable response tampering, buffering mode MUST
                // be enabled; this allows FiddlerCore to permit modification of
                // the response in the BeforeResponse handler rather than streaming
                // the response to the client as the response comes in.
                oS.bBufferResponse = false;
                Monitor.Enter(oAllSessions);
                oAllSessions.Add(oS);
                Monitor.Exit(oAllSessions);

                if ((oS.hostname == sSecureEndpointHostname) && (oS.port == 7777))
                {
                    oS.utilCreateResponseAndBypassServer();
                    oS.oResponse.headers.HTTPResponseStatus = "200 Ok";
                    oS.oResponse["Content-Type"] = "text/html; charset=UTF-8";
                    oS.oResponse["Cache-Control"] = "private, max-age=0";
                    oS.utilSetResponseBody("<html><body>Request for httpS://" + sSecureEndpointHostname + ":7777 received. Your request was:<br /><plaintext>" + oS.oRequest.headers.ToString());
                }
            };


            Fiddler.FiddlerApplication.AfterSessionComplete += delegate(
                Fiddler.Session oS)
            {
                this.Dispatcher.Invoke(
                    System.Windows.Threading.DispatcherPriority.Normal,
                    new Action(delegate()
                    {
                        txtResult.Text = String.Concat(txtResult.Text, "Finished session:\t", oS.fullUrl, Environment.NewLine);
                    }
                    ));

                if (bUpdateTitle)
                {
                    this.Dispatcher.Invoke(
                        System.Windows.Threading.DispatcherPriority.Normal,
                        new Action(delegate()
                        {
                            this.Title = ("Session list contains: " + oAllSessions.Count.ToString() + " sessions");
                        }
                        ));
                }
            };


            //Console.CancelKeyPress += new ConsoleCancelEventHandler(Console_CancelKeyPress);
            string sSAZInfo = "NoSAZ";
            this.Dispatcher.Invoke(
                System.Windows.Threading.DispatcherPriority.Normal,
                new Action(delegate()
                {
                    txtResult.Text = String.Concat(txtResult.Text, String.Format("Starting {0} ({1})...", Fiddler.FiddlerApplication.GetVersionString(), sSAZInfo), Environment.NewLine);
                }
                ));

            Fiddler.CONFIG.IgnoreServerCertErrors = false;
            FiddlerApplication.Prefs.SetBoolPref("fiddler.network.streaming.abortifclientaborts", true);

            FiddlerCoreStartupFlags oFCSF = FiddlerCoreStartupFlags.Default;
            Fiddler.FiddlerApplication.Startup(8877, oFCSF);

            FiddlerApplication.Log.LogString("Starting with settings: [" + oFCSF + "]");
            FiddlerApplication.Log.LogString("Using Gateway: " + ((CONFIG.bForwardToGateway) ? "TRUE" : "FALSE"));


        }
        ~MainWindow()
        {

            Fiddler.FiddlerApplication.Shutdown();
        }

        
        
        PostSubmitter s = new PostSubmitter("");

        private void button1_Click(object sender, RoutedEventArgs e)
        {
           /* s.Type = PostSubmitter.PostTypeEnum.Post;
            for (int i = 0; i < 5; i++)
            {
                String result = s.Post();
                File.WriteAllText("test"+i+".txt", result);
                parseFile("test"+i+".txt");
            }*/

            //String result = File.ReadAllText("test.txt");

            //s.Type = PostSubmitter.PostTypeEnum.Get;
            //String result = s.Post("http://www.quizaction.de/entertainment/games/quiz");

            //string[] OldWords = { "&nbsp;", "&amp;", "&quot;", "&lt;", "&gt;", "&reg;", "&copy;", "&bull;", "&trade;" };
            //string[] NewWords = { " ", "&", "\"", "<", ">", "Â®", "Â©", "â€¢", "â„¢" };
            //for(int i = 0; i < OldWords.Length; i++)
            //{
            //    result = result.Replace(OldWords[i], NewWords[i]);
            //}



            //int start = result.IndexOf("/content/get-ajax.php?");
            //int ende = result.IndexOf("'", start + 1);
            //String url = result.Substring(start, ende - start);
            //String temp = s.Post("http://www.quizaction.de" + url);

            //String result2 = s.Post("http://www.quizaction.de/entertainment/games/quiz");


            //parseFile("test.txt");

            Fiddler.FiddlerApplication.Shutdown();
        }

        //bool useAfter(ref String result, String after)
        //{
        //    result = result.Substring(result.IndexOf(after) + after.Length).Trim();
        //    return true;
        //}
        //String getBefore(String result, String after)
        //{
        //    return result.Substring(0, result.IndexOf(after));
        //}
        //String getBeforeAndUseAfter(ref String result, String after)
        //{
        //    String res = getBefore(result, after);
        //    useAfter(ref result, after);
        //    return res;

        //}


        //bool parseFile(String filename)
        //{
        //    TabItem t = new TabItem();
        //    QuizEntry entry = new QuizEntry();
        //    QuizEntryControl q = new QuizEntryControl();
        //    q.DataContext = entry;


        //    String result = File.ReadAllText(filename);

        //    result = result.Substring(result.IndexOf("<h2 class=\"hquiz\">") + "<h2 class=\"hquiz\">".Length);
        //    result = result.Substring(0, result.IndexOf("</ul>"));

        //    string[] OldWords = { "&nbsp;", "&amp;", "&quot;", "&lt;", "&gt;", "&reg;", "&copy;", "&bull;", "&trade;" };
        //    string[] NewWords = { " ", "&", "\"", "<", ">", "Â®", "Â©", "â€¢", "â„¢" };
        //    for (int i = 0; i < OldWords.Length; i++)
        //    {
        //        result = result.Replace(OldWords[i], NewWords[i]);
        //    }

        //    entry.TitleDE = getBeforeAndUseAfter(ref result, "</h2>");
        //    useAfter(ref result, "<span>A:</span>");
        //    entry.Answer1DE = getBefore(result, "</a>");
        //    useAfter(ref result, "<span>B:</span>");
        //    entry.Answer2DE = getBefore(result, "</a>");
        //    useAfter(ref result, "<span>C:</span>");
        //    entry.Answer3DE = getBefore(result, "</a>");
        //    useAfter(ref result, "<span>D:</span>");
        //    entry.Answer4DE = getBefore(result, "</a>");


        //    t.Content = q;
        //    t.Header = tabControl1.Items.Count + "";
        //    tabControl1.Items.Add(t);
        //    tabControl1.SelectedIndex = tabControl1.SelectedIndex + 1;

        //    return true;
        //}
    }
}
